package mips.instructions;

/**
 * <code>SLTU</code> instruction<br/>
 * Set On Less Than Unsigned<br/>
 * @author jnmartin84@gmail.com
 */
public class SLTU extends Instruction {

	private static final SLTU INSTANCE = new SLTU();
	private static final String INSTRUCTION_NAME = "SLTU";

	private SLTU(){}

	public static final SLTU getInstance() {
		return INSTANCE;
	}

	/**
	 * <b>Format:</b><br/>
	 * SLTU rd, rs, rt<br/><br/>
	 * <b>Description:</b><br/>
	 * The contents of general register rt are subtracted from the contents of<br/>
	 * general register rs. Considering both quantities as unsigned integers, if the<br/>
	 * contents of general register rs are less than the contents of general register<br/>
	 * rt, the result is set to one; otherwise the result is set to zero.<br/><br/>
	 * The result is placed into general register rd.<br/><br/>
	 * No integer overflow exception occurs under any circumstances. The<br/>
	 * comparison is valid even if the subtraction used during the comparison<br/>
	 * overflows.<br/><br/>
	 * <b>Operation:</b><br/>
	 * T: if (0 || GPR[rs]) < (0 || GPR[rt]) then<br/>
	 * GPR[rd] &larr; 0<sup>31</sup> || 1<br/>
	 * else<br/>
	 * GPR[rd] &larr; 0<sup>32</sup><br/>
	 * endif
	 */
	@Override
	public final void execute(final int instruction) {
		
		final int rs = (instruction >> 21) & 0x0000001F;
		final int rt = (instruction >> 16) & 0x0000001F;
		final int rd = (instruction >> 11) & 0x0000001F;

		final long _rs = (long) (mips.R4300i.GPR[rs] & 0x00000000FFFFFFFFL);
		final long _rt = (long) (mips.R4300i.GPR[rt] & 0x00000000FFFFFFFFL);
		
		mips.R4300i.GPR[rd] = (_rs < _rt) ? 1 : 0;
		
		mips.R4300i.PC = mips.R4300i.nPC;
		mips.R4300i.nPC = mips.R4300i.PC + 4;
	}
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public final String emit(final int instruction) {
		
		final int rs = (instruction >> 21) & 0x0000001F;
		final int rt = (instruction >> 16) & 0x0000001F;
		final int rd = (instruction >> 11) & 0x0000001F;
		
		return	"		u32_gpr_rs = (long) (mips.R4300i.GPR["+rs+"] & 0x00000000FFFFFFFFL);\n" + 
				"		u32_gpr_rt = (long) (mips.R4300i.GPR["+rt+"] & 0x00000000FFFFFFFFL);\n" + 
				"		\n" + 
				"		mips.R4300i.GPR["+rd+"] = (u32_gpr_rs < u32_gpr_rt) ? 1 : 0;\n" + 
				"		\n" + 
				"		mips.R4300i.PC = mips.R4300i.nPC;\n" + 
				"		mips.R4300i.nPC = mips.R4300i.PC + 4;";
	}
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public final String getName(final int instruction) {
		return getName();
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public final String getName() {
		return INSTRUCTION_NAME;
	}
}